import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:ost_flutter_module/class/entity/store/store_region_entity.dart';
import 'package:ost_flutter_module/network/base_request_model.dart';
import 'package:ost_flutter_module/network/completable_action.dart';
import 'package:ost_flutter_module/network/http_manager.dart';
import 'package:ost_flutter_module/network/url_constants.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:uuid/uuid.dart';

import '../../../../main.dart';

part 'city_page_event.dart';
part 'city_page_state.dart';

class CityPageBloc extends Bloc<CityPageEvent, CityPageState> {
  CityPageBloc() : super(CityPageInitial());

  BaseRequestListModel<StoreRegionEntity> _dataModel =
      BaseRequestListModel<StoreRegionEntity>();
  BaseRequestListModel<StoreRegionEntity> get dataModel => _dataModel;

  @override
  Stream<CityPageState> mapEventToState(
    CityPageEvent event,
  ) async* {
    if (event is CityPageFetchData) {
      yield* _mapFetchRegion(event);
    }
  }

  Stream<CityPageFetchSuccess> _mapFetchRegion(CityPageFetchData event) async* {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreRegionEntity>(
      store_course_region,
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    if (result.isSuccess) {
      var list = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      logger.e(result.exceptionOrNull?.showMsg);
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }

    event.action?.completer?.complete(true);
    yield CityPageFetchSuccess(Uuid().v4());
  }
}
